package com.fmn.dots_final_i_hope;

import java.util.ArrayList;
import java.util.Collections;

import android.widget.ImageView;
import model.GameField;
import model.Line;
import model.Square;

public class BotControl {
	
	public static void doAITurn(ImageView[][] gameField) {
		// squares = GameField.extractSquares(gameField);
		// Collections.shuffle(squares);
		pressAILine(gameField);
//		squares.clear();

		if (PlayerControl.getCurrentPlayer().equals(PlayerControl.p2)
				&& !PlayerControl.checkForEndGame()) {
			doAITurn(gameField);
		}

	}

	public static void pressAILine(ImageView[][] gameField) {
		final int BEST_CASE_OF_SQUARE_LINES = 1;
		final int NORMAL_CASE_OF_SQUARE_LINES = 3;
		final int NORMAL_CASE_OF_SQUARE_LINES_2 = 4;
		final int WORST_CASE_OF_SQUARE_LINES = 2;

		ArrayList<Square> squares = GameField.extractSquares(gameField);
		Collections.shuffle(squares);


		for (Square sq : squares) {
			if (sq.getNumOfNotPressedLines() == BEST_CASE_OF_SQUARE_LINES) {
				findWhichLineToPress(sq);
				return;
			}
		}
		for (Square sq : squares) {
			if (sq.getNumOfNotPressedLines() == NORMAL_CASE_OF_SQUARE_LINES
					|| sq.getNumOfNotPressedLines() == NORMAL_CASE_OF_SQUARE_LINES_2) {
				findWhichLineToPress(sq);
				return;
			}
		}
		for (Square sq : squares) {
			if (sq.getNumOfNotPressedLines() == WORST_CASE_OF_SQUARE_LINES) {
				findWhichLineToPress(sq);
				return;
			}
		}

	}

	public static void findWhichLineToPress(Square sq) {
		ArrayList<Line> arrayWithLines = new ArrayList<Line>();

		if (!sq.getLeftLine().isPressed())
			arrayWithLines.add(sq.getLeftLine());
		if (!sq.getRightLine().isPressed())
			arrayWithLines.add(sq.getRightLine());
		if (!sq.getUpperLine().isPressed())
			arrayWithLines.add(sq.getUpperLine());
		if (!sq.getDownLine().isPressed())
			arrayWithLines.add(sq.getDownLine());

		Collections.shuffle(arrayWithLines);

		PlayerControl.doAPlayerTurn(arrayWithLines.get(0));
	}

}
